%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Marginal Effect for model 3: with endog effect, no contextual, no unobs, without dummies %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% To study the marginal effect, consider an individual in a specific
%%%% group. So first, find a group

bnew1=bnew;
gg=71;  %% Find the groups whose mean characteristics is closest to the population.
            
X_f = dat(gg).xt;

n=size(X_f,1);

k=17;

bnew=bnew(1:2*k+1,:);
W_f= dat(gg).wt;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
indpv=[X_f W_f*X_f ones(n,1)];
F=1./(1+exp(-2*(indpv*bnew)));

naivemarg=[2*diag(F.*(1-F))*(bnew(1)+.2*indpv(:,1)*bnew(17)) 2*F.*(1-F)*[bnew(2:16)' bnew(18:34)']]; 
naivemargm=mean(naivemarg(1:n,:))'*100;  

ini=zeros(n,k-1);
affect=zeros(n,k-1);
X_fa=X_f;  
for member=1:n   
    %%%%% Marginal effect for the continuous variables
    kk=2;  %%% years in school
    dXdx=zeros(size(X_f));
    dXdx(member,kk)=1;
  
    amarg=2*diag(F.*(1-F))*(dXdx*bnew(1:k)+W_f*dXdx*bnew(k+1:2*k)); %% marginal effect for ALL members
    ini(member,kk)=amarg(member);
    amarg(member)=0;
    affect(:,kk)=affect(:,kk)+amarg;

    kk=1; %%% age
    dXdx=zeros(size(X_f));
    dXdx(member,kk)=1;
    dXdx(member,kk+16)=2/10*X_f(member,1);
   
    amarg=2*diag(F.*(1-F))*(dXdx*bnew(1:k)+W_f*dXdx*bnew(k+1:2*k)); %% marginal effect for ALL members
    ini(member,kk)=amarg(member);
    amarg(member)=0;
    affect(:,kk)=affect(:,kk)+amarg;

  
    %%%%% Marginal effect for the discrete variables

    for kk=3:k-1   %%%to k-1 ,as the last regressor is squared-age

        X_fa(member,kk)=0;
 
        indpv=[X_fa W_f*X_fa ones(n,1)];%
        F_before=1./(1+exp(-2*indpv*bnew));

        X_fa(member,kk)=1;

        indpv=[X_fa W_f*X_fa ones(n,1)];%
        F_after=1./(1+exp(-2*indpv*bnew));
        clear xx_new
        clear euclid
        clear x0


        amarg=F_after-F_before;
        ini(member,kk)=amarg(member);
        amarg(member)=0;
        affect(:,kk)=affect(:,kk)+amarg;

      
        X_fa=X_f;
    end
end

ma1=mean(ini);  %%% average marginal effect of initiators
ma2=mean(affect)/n;%%% average marginal effect of followers
ma=[ma1; ma2]'*100 %%% By multiply by 100, express in terms of percentage point
naivemargm;
naivemargm2=ma(:,1);
[naivemargm naivemargm2];
naive=naivemargm2


